﻿using IPBoss.Copyright.Entities;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IPBoss.Copyright.UtilityHelper
{
    public class Log4NetHelper
    {
        public static readonly log4net.ILog logInfo = log4net.LogManager.GetLogger("InfoLog");
        public static readonly log4net.ILog logError = log4net.LogManager.GetLogger("Error");
        private ILog _Ilog = null;
        private Log4NetHelper(Type t)
        {
            // 通常情况下，通过 LogManager.GetLogger() 来获取一个记录器。
            // LogManager 内部维护一个 hashtable，保存新创建 Logger 引用，下次需要时直接从 hashtable 获取其实例。
            _Ilog = log4net.LogManager.GetLogger(t);
        }
        public static void SetUserID(int UserID)
        {
            log4net.LogicalThreadContext.Properties["UserId"] = UserID;
            log4net.GlobalContext.Properties["UserId"] = UserID;
        }
        public static void Error(string message, object obj = null, Exception ex = null)
        {
            if (logError.IsErrorEnabled)
            {
                if (obj != null)
                    message = message + ":" + JsonHelper.Serialize(obj);
                logError.Error(message, ex);
            }
        }
        public static void Info(string message, object obj = null)
        {
            if (logInfo.IsInfoEnabled)
            {
                if (obj != null)
                    message = message + ":" + JsonHelper.Serialize(obj);
                logInfo.Info(message);
            }
        }
        public static Log4NetHelper Create(Type t)
        {
            return new Log4NetHelper(t);
        }
        public void Error(string msg, Exception ex = null, object obj = null)
        {
            if (obj != null)
                msg = msg + ":" + JsonHelper.Serialize(obj);
            logError.Error(msg, ex);
        }
        public void Debug(string msg, object obj = null)
        {

            if (obj != null)
                msg = msg + ":" + JsonHelper.Serialize(obj);
            if (msg.Length > 11500)
            {
                logInfo.Debug(msg.Substring(0, 3999));
            }
            else if (msg.Length > 3999)
            {
                string tmp = msg.Substring(0, 3999);
                logInfo.Debug(tmp);
                Debug(msg.Substring(3999, msg.Length - 3999));
            }
            else
                logInfo.Debug(msg);
        }
        public void Info(string methodName, string msg, object obj = null)
        {
            msg = methodName + ":" + msg;
            if (obj != null)
                msg = msg + ":" + JsonHelper.Serialize(obj);
            logInfo.Info(msg);
        }
    }
}
